#include <stdio.h>
#include <getch.h>
#include <string.h>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "tools.h"
#include <stdlib.h>
using namespace std;

bool check_book(const char *str1,char *str2)
{
	unsigned int i=0,j=0;
	while(i<strlen(str1))
	{
		if(str1[i++] == str2[j])
		j++;
	}
	if(j == strlen(str2)) return true;
	else return false;
}

void clear_buf(void)
{
	stdin->_IO_read_ptr = stdin->_IO_read_end;
}

int get_id(int num)
{
	int id[3] = {0};
	
	int fd = open("id.dat",O_RDWR);
	if(0 > fd)
	{
		perror("open");
		return -1;
	}

	if(0 >= read(fd,id,sizeof(id)))
	{
		perror("read");
		return -1;
	}

	id[num]++;	

	lseek(fd,SEEK_SET,0);

	if(0 >= write(fd,id,sizeof(id)))
	{
		perror("write");
		return -1;
	}

	close(fd);
	
	return id[num];
}

int generator_MgrId(void)
{
	int num = 0;
	return get_id(num);
}

int generator_BookId(void)
{
	int num =1;
	return get_id(num);
}

int generator_ReaderId(void)
{
	int num = 2;
	return get_id(num);
}

void anykey_continue(void)
{
	clear_buf();
	printf("请输入任意键继续...");
	getch();
	printf("\n");
}

int init_id(void)
{
	if(!access("id.dat",F_OK))
	{
		return 0;
	}

	int fd = open("id.dat",O_WRONLY | O_CREAT | O_TRUNC,0644);
	if(0 > fd)
	{
		perror("open");
		return -1;
	}

	int id_num[3] = {100,10000,1000};
	if(0 >= write(fd,id_num,sizeof(id_num)))
	{
		perror("error");
		return -1;
	}

	close(fd);

	return 0;
}

